package com.qyhl.webtv.module_broke.scoop.addscoop;

import android.annotation.SuppressLint;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.launcher.ARouter;
import com.google.gson.Gson;
import com.qyhl.webtv.basiclib.utils.DESedeUtil;
import com.qyhl.webtv.basiclib.utils.network.EasyHttp;
import com.qyhl.webtv.basiclib.utils.network.callback.SimpleCallBack;
import com.qyhl.webtv.basiclib.utils.network.exception.ApiException;
import com.qyhl.webtv.basiclib.utils.network.model.ApiResult;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ServicePathConstant;
import com.qyhl.webtv.commonlib.entity.UpTokenBean;
import com.qyhl.webtv.commonlib.service.IntergralService;
import com.qyhl.webtv.commonlib.utils.qiniu.QiniuUpload;
import com.qyhl.webtv.commonlib.utils.qiniu.UpImageLoadResultListener;
import com.qyhl.webtv.module_broke.common.BrokeUrl;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by qyhl on 2017/12/11.
 */

public class ScoopAddModel implements ScoopAddContract.ScoopAddModel {
    private ScoopAddPresenter mPresenter;
    @Autowired(name = ServicePathConstant.INTERGRAL_SERICE)
    public IntergralService intergralService;

    public ScoopAddModel(ScoopAddPresenter mPresenter) {
        this.mPresenter = mPresenter;
        ARouter.getInstance().inject(this);
    }

    @Override
    public void getToken() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String time = sdf.format(new Date());
        String code = "Z5" + time + "I2863";
        String url = CommonUtils.getInstance().getCircleUrl() + "?timestamp=" + time;

        EasyHttp.post(url)
                .upBytes(DESedeUtil.encryptMode(code, "siteId=" + CommonUtils.getInstance().getSite() + "&method=getUpToken&type=3"))
                .isDecrypt(true)
                .decryptKet(code)
                .execute(new SimpleCallBack<UpTokenBean>() {
                    @Override
                    public void onError(ApiException e) {

                    }

                    @Override
                    public void onSuccess(UpTokenBean upTokenBean) {
                        mPresenter.getTokenSuccess(upTokenBean);
                    }
                });

    }

    @Override
    public void commit(String anonymous, String title, String content, String type, String author, String plateId, String creator, String creatorAvatar, String audioDuration, String phone, String address, List<String> list, int isprivate, String token, String prefix) {
        final HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("siteId", CommonUtils.getInstance().getSite() + "");
        hashMap.put("anonymous", anonymous);
        hashMap.put("title", title);
        hashMap.put("content", content);
        hashMap.put("author", author);
        hashMap.put("plateId", plateId);
        hashMap.put("creator", creator);
        hashMap.put("creatorAvatar", creatorAvatar);
        hashMap.put("audioDuration", audioDuration);
        hashMap.put("phone", phone);
        hashMap.put("address", address);
        hashMap.put("isPrivate", String.valueOf(isprivate));
        if (list == null || list.isEmpty()) {
            hashMap.put("type", "0");
            commitService(hashMap);
        } else {
            hashMap.put("type", type);
            QiniuUpload.getQiniuUpload().upLoadImages(list, token, prefix, new UpImageLoadResultListener() {
                @Override
                public void uplaodError() {

                }

                @Override
                public void uploadSuccess(List<String> resultFiles) {
                    StringBuilder imgs = new StringBuilder();
                    if (resultFiles != null) {
                        for (String s : resultFiles) {
                            imgs.append(s);
                            imgs.append(",");
                        }
                        imgs.deleteCharAt(imgs.length() - 1);
                    }
                    hashMap.put("imagesStr", imgs.toString());
                    commitService(hashMap);
                }

                @Override
                public void uploadSingleSuccess(String path) {

                }

                @Override
                public void uploadPre(double percent) {

                }
            });
        }
    }


    @Override
    public void commit(String anonymous, String title, String content, String type, String author, String plateId, String creator, String creatorAvatar, String audioDuration, String phone, String address, File file, String mVideoCoverPath, int isprivate, String token, String prefix) {
        final HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("siteId",CommonUtils.getInstance().getSite() + "");
        hashMap.put("anonymous", anonymous);
        hashMap.put("title", title);
        hashMap.put("content", content);
        hashMap.put("author", author);
        hashMap.put("plateId", plateId);
        hashMap.put("creator", creator);
        hashMap.put("creatorAvatar", creatorAvatar);
        hashMap.put("audioDuration", audioDuration);
        hashMap.put("phone", phone);
        hashMap.put("address", address);
        hashMap.put("isPrivate", String.valueOf(isprivate));
        if (file == null) {
            hashMap.put("type", "0");
            commitService(hashMap);
        } else {
            hashMap.put("type", type);
            List<String> list = new ArrayList<>(1);
            list.add(file.getAbsolutePath());
            list.add(mVideoCoverPath);
            QiniuUpload.getQiniuUpload().upLoadImages(list, token, prefix, new UpImageLoadResultListener() {
                @Override
                public void uplaodError() {

                }

                @Override
                public void uploadSuccess(List<String> resultFiles) {
                    for (String s : resultFiles) {
                        if (s.endsWith(".mp4")) {
                            hashMap.put("videoUrl", s);
                        } else {
                            hashMap.put("videoCover", s);
                        }
                    }
                    commitService(hashMap);
                }

                @Override
                public void uploadSingleSuccess(String path) {

                }

                @Override
                public void uploadPre(double percent) {

                }
            });
        }
    }

    private void commitService(HashMap<String, String> hashMap) {
        @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String time = sdf.format(new Date());
        String code = "Z5" + time + "I2863";
        String url = BrokeUrl.ADD_SCOOP + "?timestamp=" + time;
        StringBuffer content = new StringBuffer();
        for (Map.Entry<String, String> entry : hashMap.entrySet()) {
            content = content.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        String content1 = content.toString().substring(0, content.length() - 1);

        EasyHttp.post(url)
                .upBytes(DESedeUtil.encryptMode(code, content1))
                .isDecrypt(true)
                .decryptKet(code)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
                        mPresenter.commitError("网络异常，提交失败！");
                    }

                    @Override
                    public void onSuccess(String s) {
                        ApiResult apiResult = new Gson().fromJson(s,ApiResult.class);
                        if (apiResult.getCode() == 200) {
                            mPresenter.commitSuccess("提交成功，等待审核！");
                        } else {
                            mPresenter.commitError("出错啦，提交失败！");
                        }
                    }
                });



    }


    /* 随机生成名称
     * @return
     */
    private String randomName() {
        String name = UUID.randomUUID().toString() + ".mp3";
        return name;
    }
}